package m.jclecai.com.adapter.holder;

import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.bean.ZqItem;
import m.jclecai.com.dialog.BjdcHHDialog;
import m.jclecai.com.listener.MyNotifyTextViewSetChanged;
import m.jclecai.com.listener.OnSclestListener;
import m.jclecai.com.utils.Utils;
import m.jclecai.com.utils.http.FastOk;

/**
 * Created by ZD on 2017/5/6.
 */

public class BetBjdcHolder extends ViewHolder implements View.OnClickListener {
    @BindView(R.id.betting_item_delete)
    ImageView bettingItemDelete;
    @BindView(R.id.home_team_name)
    TextView homeTeamName;
    @BindView(R.id.jclq_fen_name)
    TextView jclqFenName;
    @BindView(R.id.away_team_name)
    TextView awayTeamName;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.tv_lottery)
    CheckBox tvLottery;
    @BindView(R.id.llspf)
    LinearLayout llspf;
    @BindView(R.id.iv_split)
    ImageView ivSplit;
    @BindView(R.id.betting_item_parent)
    LinearLayout bettingItemParent;
    @BindView(R.id.cb_dan)
    public CheckBox cb_dan;
    String[] spf;
    //上下单双
    @BindView(R.id.ll_ds)
    LinearLayout ll_ds;

    @BindView(R.id.ll_hunhe_bet)
    LinearLayout mLlHunTouBet;

    @BindView(R.id.ll_all)
    LinearLayout mLlZjq;

    @BindView(R.id.ll_dan_guan)
    LinearLayout mLlDanGuan;

    ZqItem mItem;
    int mPosition = 0;
    //记录点击的数据
    Map<String, Map<String, String>> cMap;
    MyNotifyTextViewSetChanged changed;
    int mType = 0;
    int pager = 0;
    String[] codes;

    private DefaultPresenter mDefaultPresenter;
    private SPFPresenter mSPFPresenter;
    private ZjqPresenter mZjqPresenter;
    private SXDSPresenter mSXDSPresenter;

    public BetBjdcHolder(Context context, @LayoutRes int resource) {
        super(context, resource);
    }

    private void init() {
        init(this.mItem, pager, mPosition);
    }

    public void init(ZqItem item, int pager, int position) {
        this.pager = pager;
        this.mPosition = position;
        this.mItem = item;
        this.mType = pager;
        spf = getContext().getResources().getStringArray(
                R.array.jczq_spf);
        codes = item.getCodes();
        List<String[]> list = FastOk.getList(codes[15], String[].class);
        //左边队名-公共属性
        homeTeamName.setText(codes[3]);
        //右边队名-公共属性
        awayTeamName.setText(codes[4]);
        tvLottery.setVisibility(GONE);
        llspf.setVisibility(GONE);
        ll_ds.setVisibility(GONE);

        //这里默认不然其他的内容显示；
        mLlDanGuan.setVisibility(View.GONE);
        mLlHunTouBet.setVisibility(View.GONE);
        mLlZjq.setVisibility(View.GONE);

        cb_dan.setChecked(item.isDan_select());

        mDefaultPresenter = new DefaultPresenter();
        mSPFPresenter = new SPFPresenter();
        mZjqPresenter = new ZjqPresenter();
        mSXDSPresenter = new SXDSPresenter();

        if(pager == 0){
            mSPFPresenter.init(mItem);
        }else if(pager == 2){
            mZjqPresenter.init(mItem);
        }else if(pager == 4){
            mSXDSPresenter.init(mItem);
        }else{
            //这里是一个默认的处理的操作；
            mDefaultPresenter.init(mItem);
        }

       /* if (pager == 4) {//上下单双
            ll_ds.setVisibility(VISIBLE);
            initDS(list);
        } else if (pager > 0) {
            tvLottery.setVisibility(VISIBLE);
            resetCheckBoxStatus(tvLottery, "点击选择比分");
        } else {
            llspf.setVisibility(VISIBLE);
            initSPF(list);
        }*/
    }

    void initSPF(List<String[]> strList) {
        //当前采种下面有几种比例选项 llspf
        String[] strings = strList.get(mType);
        for (int i = 0; i < strings.length; i++) {
            jclqFenName.setText(String.valueOf(codes[5]));
            jclqFenName.setTextColor(ContextCompat.getColor(getContext(), R.color.o));
            if (codes[5].startsWith("+"))
                jclqFenName.setTextColor(ContextCompat.getColor(getContext(), R.color.font_red));
            else if (codes[5].startsWith("-"))
                jclqFenName.setTextColor(ContextCompat.getColor(getContext(), R.color.color_0b7e07));
            CheckBox cb = (CheckBox) llspf.getChildAt(i);
            cb.setOnClickListener(this);
            StringBuilder tag = new StringBuilder();
            tag.append(mType == 0 ? "0_spf" : "1_rqspf");
            tag.append("_" + i + "_" + strings[i]);
            if (i == 1) {
                cb.setText("平" + strings[i]);
                tag.append("_平");
            } else if (i == 0) {
                cb.setText("胜" + strings[i]);
                tag.append("_胜");
            } else if (i == 2) {
                cb.setText("负" + strings[i]);
                tag.append("_负");
            }
            tag.append("_" + spf[i]);
            cb.setTag(tag.toString());
            cb.setChecked(isCheckThisView(cb.getTag().toString(), String.valueOf(pager)));
        }
    }

    void initDS(List<String[]> strList) {
        int childCount = ll_ds.getChildCount();
        int index = 0;
        String[] names = new String[]{"上单", "上双", "下单", "下双"};
        String[] strs;
        if (strList == null)
            strs = new String[]{"0", "0", "0", "0"};
        else
            strs = strList.get(1);
        //大小单双的值上单3 上双2 下单1 下双0
        for (int i = 0; i < childCount; i++) {
            ViewGroup childAt = (ViewGroup) ll_ds.getChildAt(i);
            for (int j = 0; j < childAt.getChildCount(); j++) {
                CheckBox cb = (CheckBox) childAt.getChildAt(j);
                StringBuilder tag = new StringBuilder("3_sxp_" + index + "_" + strs[index] + "_" + names[index] + "_" + (3 - index));
                cb.setOnClickListener(this);
                cb.setTag(tag.toString());
                StringBuilder sb = new StringBuilder();
                sb.append(names[index]);
                sb.append("<br/><small><small>");
                sb.append(strs[(3 - index)]);
                sb.append("</small></small>");
                cb.setText(Html.fromHtml(sb.toString()));
                cb.setChecked(isCheckThisView(cb.getTag().toString(), "3"));
                index++;
            }
        }
    }

    /**
     * 解析tag参数
     *
     * @param tag
     * @return
     */
    boolean isCheckThisView(String tag, String index) {
        if (this.mItem.getMap() == null) return false;
        if (this.mItem.getMap().get(index) != null) {
            return this.mItem.getMap().get(index).get(tag) != null;
        }
        return false;
    }

    //显示纯文本
    String showTextUi() {
        //到时候这个排序可以提到外面去 减少计算时间
        Map<String, Map<String, String>> map = mItem.getMap();
        //将key 排序然后显示
        StringBuilder sb = new StringBuilder();
        for (Map<String, String> strMap : map.values()) {
            //勾选的数据 "0_spf_0_2.25_胜" -> "0_spf_0_2.25_胜"
            // 0-服务器数据下标，spf 类型 0-点击的下标用来排序 2.25倍数 胜显示的值
            String[] strs = strMap.keySet().toArray(new String[]{});
            int[] arrayKey = new int[strs.length];
            Map<Integer, String> nMap = new HashMap<>();
            //排序
            for (int j = 0; j < strs.length; j++) {
                String[] split = strs[j].split("_");
                arrayKey[j] = Integer.parseInt(split[2]);
                nMap.put(arrayKey[j], strs[j]);
            }
            Arrays.sort(arrayKey);
            //输出
            for (int j = 0; j < arrayKey.length; j++) {
                String keys = nMap.get(arrayKey[j]);
                String[] split = keys.split("_");
                if (("rqspf").equals(split[1]))
                    sb.append("让");
                sb.append(split[4]);
                if ("jqs".equals(split[1]))
                    sb.append("球");
                sb.append(" ");
            }
        }
        return sb.toString();
    }

    //混投点击更多玩法
    @OnClick(R.id.tv_lottery)
    void more(View v) {
        execCheckParam((CheckBox) v, "点击选择比分");
    }

    /**
     * 处理选中的数据与ui交互
     *
     * @param cb
     * @param buttonText
     */
    void execCheckParam(final CheckBox cb, final String buttonText) {
        resetCheckBoxStatus(cb, buttonText);
        BjdcHHDialog.SHOWTYPE type;
        if (pager == 1) {
            type = BjdcHHDialog.SHOWTYPE.SHOWBF;
        } else if (pager == 2) {
            type = BjdcHHDialog.SHOWTYPE.SHOWZJQ;
        } else if (pager == 3) {
            type = BjdcHHDialog.SHOWTYPE.SHOWBQC;
        } else {
            type = BjdcHHDialog.SHOWTYPE.SHOWALL;
        }
        BjdcHHDialog dialog = new BjdcHHDialog(getContext(), this.mItem.getCodes(), this.mItem.getMap(), type);
        dialog.setListener(new OnSclestListener() {
            @Override
            public void sure(Map<String, Map<String, String>> map) {
                if (mItem.getMap() != null)
                    mItem.getMap().clear();
                mItem.setMap(map);
                String desc = showTextUi();
                cb.setText(desc);
                cb.setChecked(!buttonText.equals(desc));
                init();
                statistics();
            }
        });
        dialog.show();
    }

    //重置投注按钮状态(CheckBox)
    void resetCheckBoxStatus(final CheckBox cb, final String buttonText) {
        //设置默认选中
        String desc = mItem.getMap() != null && mItem.getMapLength() > 0 ? showTextUi() : buttonText;
        cb.setText(desc);
        cb.setChecked(!buttonText.equals(desc));
    }

    //分割线
    public void isShowSplit(boolean show) {
        ivSplit.setVisibility(show ? VISIBLE : GONE);
    }

    @Override
    public void onClick(View v) {
        checkButtonDoClick(v);
    }

    /**
     * 这里是复选按钮的点击事件处理
     */
    public void checkButtonDoClick(View view){
        if (mItem.getMap() == null) {
            cMap = new HashMap<>();
            mItem.setMap(cMap);
        } else {
            cMap = mItem.getMap();
        }
        String tag = view.getTag().toString();
        String key = tag.substring(0, 1);
        String value = tag;
        if (cMap.get(key) != null) {
            //有则删除 无则添加 - 等同于没选中则选中 选中了则取消
            if (cMap.get(key).get(value) != null) {
                cMap.get(key).remove(value);
            } else {
                cMap.get(key).put(value, value);
            }
        } else {
            Map<String, String> map = new HashMap<>();
            map.put(value, value);
            cMap.put(key, map);
        }
        statistics();
    }

    @OnClick(R.id.betting_item_delete)
    void delete() {
        if (Utils.ZQ_ITEM_LIST.contains(mItem)) {
            Utils.ZQ_ITEM_LIST.remove(mItem);
            if (changed != null)
                changed.refreshData();
        }
    }

    //胆码
    @OnClick(R.id.cb_dan)
    void checkDan() {
        mItem.setDan_select(cb_dan.isChecked());
        if (getCheckDan() > Utils.ZQ_ITEM_LIST.size() - 1) {
            cb_dan.setChecked(false);
            mItem.setDan_select(cb_dan.isChecked());
            Toast.makeText(getContext(), "胆码场次超过限制", Toast.LENGTH_SHORT).show();
            return;
        }
        if (changed != null)
            changed.onClickSetChangedText();
    }

    public int getCheckDan() {
        int checkCount = 0;
        for (int i = 0; i < Utils.ZQ_ITEM_LIST.size(); i++) {
            if (Utils.ZQ_ITEM_LIST.get(i).isDan_select())
                checkCount++;
        }
        return checkCount;
    }

    //统计勾选的数据
    private void statistics() {
        if (mItem.getMapLength() > 0) {
            if (!Utils.ZQ_ITEM_LIST.contains(mItem)) {
                if (mPosition < Utils.ZQ_ITEM_LIST.size())
                    Utils.ZQ_ITEM_LIST.add(mPosition, mItem);
                else
                    Utils.ZQ_ITEM_LIST.add(mItem);
            }
        } else {
            if (Utils.ZQ_ITEM_LIST.contains(mItem)) {
                Utils.ZQ_ITEM_LIST.remove(mItem);
                if (changed != null)
                    changed.refreshData();}
        }
        if (changed != null)
            changed.onClickSetChangedText();
    }

    public void setChangeListener(MyNotifyTextViewSetChanged change) {
        this.changed = change;
    }


    //=========这里先写这么多的业务逻辑类，然后对其进行一个抽象，然后封装处理=======

    /**
     * 这里是默认的业务逻辑类；
     */
    public class DefaultPresenter{
        public void init(ZqItem zqItem){
            tvLottery.setVisibility(VISIBLE);
            resetCheckBoxStatus(tvLottery, "点击选择比分");
        }
    }

    /**
     *总击球的业务逻辑类；
     */
    public class ZjqPresenter{
        public void init(ZqItem item){
            //这里的一个业务逻辑类；
            //显示；
            mLlZjq.setVisibility(View.VISIBLE);

            List<String[]> list = FastOk.getList(item.getCodes()[15], String[].class);

            initZjq(mLlZjq,list.get(2),item.getCodes()[19]);
        }


        public void initZjq(LinearLayout llAll,String[] strCodeOdd,String danGuanInput){

            //当前采种下面有几种比例选项
            int childCount = llAll.getChildCount();//混投布局是上下两个linearlayout 每个 linearlayout下四个子view
            int index = 0;
            for (int i = 0; i < childCount; i++) {
                ViewGroup child = (ViewGroup) llAll.getChildAt(i);
                for (int j = 0; j < child.getChildCount(); j++) {
                    CheckBox cb = (CheckBox) child.getChildAt(j);

                    StringBuilder tag = new StringBuilder("2_jqs_" + index + "_" + strCodeOdd[index] + "_" + index + "_" + index);
                    cb.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            checkButtonDoClick(v);
                        }
                    });
                    StringBuilder sb = new StringBuilder();
                    sb.append(index);
                    if (i == childCount - 1 && j == child.getChildCount() - 1)
                        sb.append("球+");
                    else
                        sb.append("球");
                    sb.append("<br/><small><small>");
                    sb.append(strCodeOdd[index]);
                    sb.append("</small></small>");
                    cb.setText(Html.fromHtml(sb.toString()));
                    cb.setTag(tag.toString());
                    cb.setChecked(isCheckThisView(cb.getTag().toString(), "2"));

                    index++;
                }
            }
        }
    }

    /**
     * 这里是上下单双的业务逻辑类；
     */
    public class SXDSPresenter{
        public void init(ZqItem zqItem){
            ll_ds.setVisibility(VISIBLE);
            List<String[]> list = FastOk.getList(zqItem.getCodes()[15], String[].class);
            initDS(list);
        }
    }

    /**
     * 胜平负的业务逻辑类；
     */
    public class SPFPresenter{

        public void init(ZqItem zqItem){

            llspf.setVisibility(VISIBLE);
            List<String[]> list = FastOk.getList(zqItem.getCodes()[15], String[].class);
            initSPF(list);
        }


        void initSPF(List<String[]> strList) {
            //当前采种下面有几种比例选项 llspf
            String[] strings = strList.get(mType);
            for (int i = 0; i < strings.length; i++) {
                jclqFenName.setText(String.valueOf(codes[5]));
                jclqFenName.setTextColor(ContextCompat.getColor(getContext(), R.color.o));
                if (codes[5].startsWith("+"))
                    jclqFenName.setTextColor(ContextCompat.getColor(getContext(), R.color.font_red));
                else if (codes[5].startsWith("-"))
                    jclqFenName.setTextColor(ContextCompat.getColor(getContext(), R.color.color_0b7e07));
                CheckBox cb = (CheckBox) llspf.getChildAt(i);
                cb.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //这里做的一个操作就是点击
                        checkButtonDoClick(v);
                    }
                });
                StringBuilder tag = new StringBuilder();
                tag.append(mType == 0 ? "0_spf" : "1_rqspf");
                tag.append("_" + i + "_" + strings[i]);
                if (i == 1) {
                    cb.setText("平" + strings[i]);
                    tag.append("_平");
                } else if (i == 0) {
                    cb.setText("胜" + strings[i]);
                    tag.append("_胜");
                } else if (i == 2) {
                    cb.setText("负" + strings[i]);
                    tag.append("_负");
                }
                tag.append("_" + spf[i]);
                cb.setTag(tag.toString());
                cb.setChecked(isCheckThisView(cb.getTag().toString(), String.valueOf(pager)));
            }
        }

    }


}
